//
//  ViewController.swift
//  MeasureMould
//
//  Created by iOS on 2021/3/30.
//

import UIKit
import CoreBluetooth
import SnapKit
import MapKit

class ViewController: UIViewController {

    lazy var mapView:MAMapView = {
        let mapView = MAMapView()
        mapView.isShowsUserLocation = true
        mapView.userTrackingMode = .follow
        return mapView
    }()
    lazy var textView:UITextView = {
        let textView = UITextView()
        textView.backgroundColor = .white
        textView.textColor = .black
        textView.isEditable = false
        return textView
    }()
    lazy var startBtn:UIButton = {
        let btn = UIButton()
        btn.setTitle("开始", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.backgroundColor = .blue
        btn.layer.masksToBounds = true
        btn.layer.cornerRadius = 10
        return btn
    }()
    lazy var endBtn:UIButton = {
        let btn = UIButton()
        btn.setTitle("结束", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.backgroundColor = .blue
        btn.layer.masksToBounds = true
        btn.layer.cornerRadius = 10
        return btn
    }()
    lazy var areaLabel:UILabel = {
        let label = UILabel()
        label.textColor = .black
        label.textAlignment = .center
        label.font = UIFont.systemFont(ofSize: 15)
        return label
    }()
    lazy var areaCalLabel:UILabel = {
        let label = UILabel()
        label.textColor = .black
        label.textAlignment = .center
        label.font = UIFont.systemFont(ofSize: 15)
        return label
    }()

    lazy var exportFileBtn:UIButton = {
        let btn = UIButton()
        btn.setTitle("导出文件", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.backgroundColor = .blue
        btn.layer.masksToBounds = true
        btn.layer.cornerRadius = 10
        return btn
    }()


//    中心管理者
    var CBtManager:CBCentralManager!
//    当前服务特征
    var characteristic:CBCharacteristic?
//    当前使用的外设
    var peripheral:CBPeripheral?
//    连接的外围设备
    var peripheralList:[CBPeripheral] = []

    var polygon:MAPolygon!
    var polygonLine:MAPolyline!

    var locationManager:AMapLocationManager!

    /// 一般数据
    var locations:[CLLocationCoordinate2D] = []
    /// 实时定位数据
    var retaltimeLocas:[CLLocationCoordinate2D] = []

    var tempLocaList:[CLLocationCoordinate2D] = []

    var currentData:Data = Data()
    var realModel = RealtimeModel()

    //测试
    var latiude = 30.483768
    var longitude = 103.561824
    var mapIndex = 0


    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.mapView.setZoomLevel(17, animated: animated)
    }


    /// 配置定位
    func configLocationManager(){
        self.locationManager = AMapLocationManager()
        self.locationManager.delegate = self
        self.locationManager.distanceFilter = 0.1
        self.locationManager.desiredAccuracy = 0.1
        self.locationManager.locationTimeout = 5
        self.locationManager.pausesLocationUpdatesAutomatically = false
        self.locationManager.allowsBackgroundLocationUpdates = false
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        self.mapView.delegate = self
        self.view.addSubview(self.mapView)
        self.mapView.snp_makeConstraints { (make) in
            make.edges.equalToSuperview().offset(0)
        }

        self.view.addSubview(self.textView)
        self.textView.snp.makeConstraints { (make) in
            make.left.top.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(200)
        }

        self.startBtn.addTarget(self, action: #selector(bluetoothStar), for: .touchUpInside)
        self.view.addSubview(self.startBtn)
        self.startBtn.snp.makeConstraints { (make) in
            make.right.equalTo(self.view.snp_centerX).offset(-10)
            make.bottom.equalToSuperview().offset(-20)
            make.width.equalTo(80)
        }

        self.endBtn.addTarget(self, action: #selector(endBtnClick), for: .touchUpInside)
        self.view.addSubview(self.endBtn)
        self.endBtn.snp.makeConstraints { (make) in
            make.left.equalTo(self.view.snp_centerX).offset(10)
            make.bottom.equalToSuperview().offset(-20)
            make.width.equalTo(80)
        }

        self.view.addSubview(self.areaLabel)
        self.areaLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(self.endBtn.snp.top).offset(-20)
            make.height.equalTo(40)
        }
        self.view.addSubview(self.areaCalLabel)
        self.areaCalLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(self.areaLabel.snp.top).offset(-20)
            make.height.equalTo(40)
        }

        self.view.addSubview(exportFileBtn)
        exportFileBtn.addTarget(self, action: #selector(exportFilButtonClick), for: .touchUpInside)
        exportFileBtn.snp.makeConstraints { (make) in
            make.right.equalTo(-10)
            make.bottom.equalTo(-40)
            make.width.equalTo(80)
            make.height.equalTo(40)
        }

//        let options = [CBCentralManagerOptionShowPowerAlertKey:true, CBCentralManagerScanOptionAllowDuplicatesKey:false]
//        self.CBtManager = CBCentralManager(delegate: self, queue: DispatchQueue.global(), options: options)
//        self.CBtManager.delegate = self

        self.configLocationManager()

        //测试数据
//        var gonCoordinates:[CLLocationCoordinate2D] = [
//            CLLocationCoordinate2D(latitude: 30.799714, longitude: 103.948954),
//            CLLocationCoordinate2D(latitude: 30.798714, longitude: 103.948954),
//            CLLocationCoordinate2D(latitude: 30.797714, longitude: 103.948954),
//            CLLocationCoordinate2D(latitude: 30.797714, longitude: 103.948854),
//            CLLocationCoordinate2D(latitude: 30.797714, longitude: 103.948854),
//            CLLocationCoordinate2D(latitude: 30.797714, longitude: 103.948854)]
//        let polygon = MAPolygon(coordinates: &gonCoordinates, count: UInt(gonCoordinates.count))
//        mapView.add(polygon)
        /// 山地 定宽

        let fileManager = LocatFileManager()
        let area = fileManager.mathArea
        let permater = fileManager.mathPermater
        print("计算面积 == ",area)
        print("计算周长 === ", permater)
        print("定宽测量 === ", permater * 20)
//        print("地图计算 == ", MAAreaForPolygon(&fileManager.coordList, Int32(fileManager.coordList.count)))
        let polyLine = MAPolyline(coordinates: &fileManager.polyCoordList, count: UInt(fileManager.polyCoordList.count))
        self.mapView.add(polyLine)


        
    }

    //MARK: - 导出文件
    @objc func exportFilButtonClick(){
        let customFileManager = CustomFileManager()
        customFileManager.openDocumentInResureceFloder(view: self.view)
//        let url = URL(fileURLWithPath: customFileManager.locFileName)
//        let documentPicker = UIDocumentPickerViewController(url: url, in: .exportToService)
//        documentPicker.delegate = self
//        documentPicker.modalPresentationStyle = .formSheet
//        self.present(documentPicker, animated: true, completion: nil)
    }

    //MARK: - 开始点击事件
    @objc func bluetoothStar(){
        self.CBtManager.delegate = self
        self.retaltimeLocas.removeAll()
        mapView.remove(self.polygon)
        //开始定位
//        self.locationManager.startUpdatingLocation()

        let openGPS = "OPENGPS\r\n".data(using: .utf8)
        let mss_choice = "MSS_CHOICE\r\n".data(using: .utf8)
        let ms_model = "MS_MODE16\r\n".data(using: .utf8)
//        let mss_jizai = "MSS_JIZAI20\r\n".data(using: .utf8)
//        let mss_kuandu = "MSS_KUANDU30\r\n".data(using: .utf8)
        let mssstart = "MSSTART\r\n".data(using: .utf8)
        if self.peripheral != nil {
            self.peripheral!.writeValue(openGPS!, for: characteristic!, type: CBCharacteristicWriteType.withResponse)
            self.peripheral!.writeValue(mss_choice!, for: characteristic!, type: CBCharacteristicWriteType.withResponse)
            self.peripheral!.writeValue(ms_model!, for: characteristic!, type: CBCharacteristicWriteType.withResponse)
//            self.peripheral!.writeValue(mss_jizai!, for: characteristic!, type: CBCharacteristicWriteType.withResponse)
//            self.peripheral!.writeValue(mss_kuandu!, for: characteristic!, type: CBCharacteristicWriteType.withResponse)
//            self.peripheral!.writeValue(msstart.hexData()!, for: characteristic!, type: CBCharacteristicWriteType.withResponse)
            self.peripheral!.writeValue(mssstart!, for: characteristic!, type: CBCharacteristicWriteType.withResponse)
        }
    }

    //MARK: - 测模结束按钮事件
    @objc func endBtnClick(){
//        guard self.polygon != nil else {
//            return
//        }
        //结束定位
//        self.locationManager.stopUpdatingLocation()

//        var tempLocations:[CLLocationCoordinate2D] = []
//        var firtPoint = MAMapPointForCoordinate(self.retaltimeLocas.first!)
//        tempLocations.append(self.retaltimeLocas.first!)
//        self.retaltimeLocas.forEach { (locat) in
//            let tempPoint = MAMapPointForCoordinate(locat)
//            let distance = MAMetersBetweenMapPoints(firtPoint, tempPoint)
//            if distance < 13 {
//                tempLocations.append(locat)
//                firtPoint = tempPoint
//            }
////            let pointAnn = MAPointAnnotation()
////            pointAnn.coordinate = CLLocationCoordinate2DMake(locat.latitude, locat.longitude)
////            self.mapView.addAnnotation(pointAnn)
//        }

        mapView.remove(self.polygonLine)
        mapView.remove(self.polygon)
        self.polygon = MAPolygon(coordinates: &retaltimeLocas, count: UInt(retaltimeLocas.count))
        mapView.add(self.polygon)
        mapView.showOverlays([self.polygon as Any], animated: true)

//        self.polygonLine = MAPolyline(coordinates: &tempLocations, count: UInt(tempLocations.count))
//        self.mapView.add(self.polygonLine)
        var area:Double = 0
        if self.retaltimeLocas.count > 3 {
            // 计算多边形面积 待改进(计算不准确)
            let firtPoint = MAMapPointForCoordinate(self.retaltimeLocas.first!)
            var secondPoint = MAMapPointForCoordinate(self.retaltimeLocas[1])
            var threePoint = MAMapPointForCoordinate(self.retaltimeLocas[2])
            var distance_a = MAMetersBetweenMapPoints(firtPoint, secondPoint)
            var distance_b = MAMetersBetweenMapPoints(secondPoint, threePoint)
            var distance_c = MAMetersBetweenMapPoints(firtPoint, threePoint)
            area = hailunToArea(distance_a, b: distance_b, c: distance_c)
            for index in 0 ..< retaltimeLocas.count - 1 {
                if index >= 2 && index < retaltimeLocas.count {
                    secondPoint = MAMapPointForCoordinate(self.retaltimeLocas[index])
                    threePoint = MAMapPointForCoordinate(self.retaltimeLocas[index+1])
                    distance_a = MAMetersBetweenMapPoints(firtPoint, secondPoint)
                    distance_b = MAMetersBetweenMapPoints(secondPoint, threePoint)
                    distance_c = MAMetersBetweenMapPoints(firtPoint, threePoint)
                    area += hailunToArea(distance_a, b: distance_b, c: distance_c)
                }
            }
        }

        // 189m²
        let model = self.realModel
        self.areaLabel.text = "面积：" + String(model.rt_area) + "m²"
        self.areaCalLabel.text = "计算面积：" + String(area) + "m²"

        let msend = "MSEND\r\n".data(using: .utf8)
        let closeGPS = "CLOSEGPS\r\n".data(using: .utf8)

        if self.peripheral != nil {
            self.peripheral!.writeValue(msend!, for: characteristic!, type: CBCharacteristicWriteType.withResponse)
            self.peripheral!.writeValue(closeGPS!, for: characteristic!, type: CBCharacteristicWriteType.withResponse)

        }

//        let buffer = UnsafeMutablePointer<CLLocationCoordinate2D>.allocate(capacity: retaltimeLocas.count)
//        for (index, item) in retaltimeLocas.enumerated() {
//            buffer[index].latitude = item.latitude
//            buffer[index].longitude = item.longitude
//        }
//        let mutalLine = MAMultiPolyline(coordinates: buffer, count: UInt(retaltimeLocas.count))
//        self.mapView.add(mutalLine)
//        mapView.showOverlays([mutalLine as Any], animated: true)
//        buffer.deallocate()

    }

    func appendUIShowString(service:CBService){
        print("BT service == ", service.uuid.uuidString)
    }

    func appendUIShowCharacter(service: CBService, charactor:CBCharacteristic){
        print("BT service = \(service.uuid.uuidString) \n charactor = \(charactor.uuid.uuidString)")
    }

    func sendQueryVersioCommand(peripheral:CBPeripheral, characteristic:CBCharacteristic){
        let cmdByte:[UInt8] = [0xaa, 0x41, 0x00]
        let byteData = NSData(bytes: cmdByte, length: 3)
        peripheral.writeValue(byteData as Data, for: characteristic, type: CBCharacteristicWriteType.withResponse)
    }


}

extension ViewController:UIDocumentPickerDelegate {

}

extension ViewController:CBCentralManagerDelegate{
//    中心设备的蓝牙状态发生变化之后会调用此方法
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        switch central.state {
            case .unknown:
                print("未知的")
                break
            case .resetting:
                print("重置中")
                break
            case .unsupported:
                print("不支持")
                break
            case .unauthorized:
                print("未验证")
                break
            case .poweredOff:
                print("未启动")
                break
            case .poweredOn:
                print("可用")
                central.scanForPeripherals(withServices: nil, options: [CBCentralManagerScanOptionAllowDuplicatesKey : NSNumber.init(value: false)])
                break
            default:
                break
        }
    }
    //应用从后台恢复到前台的时候，会和系统蓝牙进行同步，调用此法
    func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any]) {
        let peripherals = dict[CBCentralManagerOptionRestoreIdentifierKey]
        print("BT peripherals == ", peripherals as Any)
        if peripherals != nil {
            for peripheral in peripherals as! [CBPeripheral] {
                self.peripheralList.append(peripheral)
                peripheral.delegate = self
            }
        }
    }

    //    中心设备发现外设的时候调用的方法
    //peripheral 外设
    //RSSI 信号
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        guard let name = peripheral.name else { return }
        print("BT peripheral.name == ", name)
        print("rssi == ", RSSI)
        print("advertisementData == ", advertisementData)
//        print("BT peripheral.name == \(name), rssi == \(RSSI), advertisementData == \(advertisementData)")
        /*
         //需要对连接的外设进行过滤
         //1.信号强度（40，80以上连接）
         //2.通过设备名
         */
        if name.hasPrefix("HYL.BT.GPS") {
            //这里必须强引用
            self.peripheralList.append(peripheral)
            //搜索到指定的外设就可以开始连接外设了
            central.connect(peripheral, options: [:])
        }
    }

    //中心设备连接上外设时候调用的方法
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        //连接成功就停止扫描
        self.CBtManager.stopScan()

        peripheral.delegate = self
        self.peripheral = peripheral
        //连接成功后开始搜索服务
        peripheral.discoverServices(nil)
    }

    //中心设备与已连接的外设断开连接时调用的方法
    func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
        print("BT didDisconnectPerpheral")
    }

    //中心设备连接外设失败时调用的方法
    func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
        print("BT didFailToConnect")
    }

}

extension ViewController:CBPeripheralDelegate{
    //发现外设服务里的特征的时候调用的代理方法(这个是比较重要的方法，你在这里可以通过事先知道的UUID找到你需要的特征，订阅特征，或者这里写入数据给特征也可以)
    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        for service in peripheral.services! {
            //外围设备查找指定服务中的特征
            print("BT service == ", service.uuid.uuidString)
            print("peripheral.name == ", String(describing: peripheral.name))
            //指定service UDID, 搜索服务成功后查找指定报务中的特征
            peripheral.discoverCharacteristics(nil, for: service)
        }
    }

    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        for characteristic in service.characteristics! {
            print("BT characteristic.properties = ", characteristic.properties)
            let discriptString = propertiesString(properties: characteristic.properties)
            print("BT characteristic.UUID.UUIDSting = ", characteristic.uuid.uuidString)
            print("discriptString = ", discriptString)
            //情景一：特征数据读取
            if (characteristic.properties.rawValue & CBCharacteristicProperties.read.rawValue) != 0 {
                peripheral.readValue(for: characteristic)
                if (characteristic.value != nil){

                    let dataString:String = String(bytes: characteristic.value!, encoding: String.Encoding.utf8)!
                    print("BT 读取到特征值 == ",dataString)
                }
            }

            //情景二：设置特征通知
            if (characteristic.properties.rawValue & CBCharacteristicProperties.notify.rawValue) != 0 {
                peripheral.setNotifyValue(true, for: characteristic)
            }

            //情景三：特征数据写入
            if (characteristic.properties.rawValue & CBCharacteristicProperties.write.rawValue) != 0 {
                //发送查询版本请求

            }
        }
    }
    //根据不同的场景，会调用以下三个方法
    func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
        if characteristic.value != nil {
            guard let data = characteristic.value else { return }
            let hexDataStr = data.hexString()
            print("hexDataStr === ", hexDataStr)
            if data.count > 0 {
                for i in 0 ..< data.count {
                    print("BT didUpdateNotificationStateFor i = \(i), value = \(characteristic.value![i])")
                }
            }
        }
    }
    //MARK: - 更新蓝牙数据
    //更新特征的value的时候会调用(凡是从蓝牙传过来的数据都要经过这个回调，简单的说这个方法就是你拿数据的唯一方法)
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        self.peripheral = peripheral
        self.characteristic = characteristic
        if error != nil {
            print("发送数据错误的特性是：\(characteristic.uuid)     错误信息：\(String(describing: error?.localizedDescription))       错误数据：\(String(describing: characteristic.value))")
            return
        }

        if characteristic.value != nil {
            guard let data = characteristic.value else { return }
            guard data.count > 0 else {
                return
            }

            if characteristic.value?.first == 36 || characteristic.value?.last == 42 {
                let model = NormalModel()
                if characteristic.value?.first! == 36{
                    if characteristic.value?.last! == 42 {
                        model.read_analyzeData(formData: data)
                    }else{
                        self.currentData = data
                    }
                }else{
                    self.currentData.append(data)
                    let hexstr = self.currentData.hexString()
                    print("未测量数据 十六进制 == ", hexstr)
                    model.read_analyzeData(formData: self.currentData)
                    model.boolthDataWithHex(hexstr)
                }
                if model.pro_longitude > 0 && model.pro_latitude > 0 {

        //            let textLocal:String = "laitude:"+latiude +"longitude:"+ longitude + "\n"
                    DispatchQueue.main.async {
//                        self.textView.text += String(format: "laitude:\(UInt(model.lat_d))°\(UInt(model.lat_m))′\(model.lat_s)″ longitude:\(UInt(model.lon_d))°\(UInt(model.lon_m))′\(model.lon_s)″\n")
                        let lat = stringWithCoordinater(coordinate: String(model.pro_latitude))
                        let lon = stringWithCoordinater(coordinate: String(model.pro_longitude))
                        self.textView.text += String(format: "laitude:\(lat) longitude:\(lon)\n")


                    }

        //            let locationCoord:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: latiude, longitude: longitude)
                    let locationCoord:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: model.pro_latitude, longitude: model.pro_longitude)
                    locations.append(locationCoord)
                    if mapIndex == 0 {
                        mapIndex = 1
                        let pointAnn = MAPointAnnotation()
                        pointAnn.coordinate = CLLocationCoordinate2DMake(model.pro_latitude, model.pro_longitude)
                        DispatchQueue.main.async {
                            self.mapView.addAnnotation(pointAnn)
                            let normalArea = hailunToArea(6, b: 6, c: 6)
                            self.areaCalLabel.text = "计算面积：" + String(normalArea) + "m²"
                        }

                    }

                }
            }
            
            /// 实时数据
            if characteristic.value?.first == 35 || characteristic.value?.last == 64 {
                let rtModel = RealtimeModel()
                if characteristic.value?.first! == 35{
                    if characteristic.value?.last! == 64 {
                        rtModel.realtimeData(formData: data)
                    }else{
                        self.currentData = data
                    }
                }else{
                    self.currentData.append(data)
                    let hexstr = self.currentData.hexString()
                    print("未测量数据 十六进制 == ", hexstr)
                    rtModel.boolthRelDataWithHex(hexstr)
                    rtModel.realtimeData(formData: self.currentData)
                }
                if rtModel.rt_longitude > 0 && rtModel.rt_laitude > 0 {

                    let locationCoord:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: rtModel.rt_laitude, longitude: rtModel.rt_longitude)

//                    let pointAnn = MAPointAnnotation()
//                    pointAnn.coordinate = CLLocationCoordinate2DMake(rtModel.rt_laitude, rtModel.rt_longitude)
//                    DispatchQueue.main.async {
//                        self.mapView.addAnnotation(pointAnn)
//                    }
                    retaltimeLocas.append(locationCoord)
                    self.realModel = rtModel

                    mapView.remove(self.polygonLine)
                    self.polygonLine = MAPolyline(coordinates: &retaltimeLocas, count: UInt(retaltimeLocas.count))
                    DispatchQueue.main.async {
                        self.mapView.add(self.polygonLine)
                    }


                    DispatchQueue.main.async {
//                        self.textView.text += String(format: "实时laitude:\(rtModel.rt_laitude) longitude:\(rtModel.rt_longitude)\n")
                        let lat = stringWithCoordinater(coordinate: String(rtModel.rt_laitude))
                        let lon = stringWithCoordinater(coordinate: String(rtModel.rt_longitude))
                        self.textView.text += String(format: "实时laitude:\(lat) longitude:\(lon)\n")
                    }
                }

            }

//            let dataStr = String(data: data, encoding: .ascii)
//            print("\(Date())didUpdateValue dataStr === ", dataStr ?? "")
            let hexDataStr = data.hexString()
            print("\(Date())didUpdateValue hexDataStr === ", hexDataStr)
            if data.count > 0 {
                for i in 0 ..< data.count {
                    print("BT didUpdateValueFor i = \(i), value = \(characteristic.value![i])")
                }
            }
        }

    }

    func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
        if error != nil {
            print("=====写入错误：",error.debugDescription)
        }else{
            print("=====写入成功")
        }
        if characteristic.value != nil {
            guard let data = characteristic.value else { return }
            let hexDataStr = data.hexString()
            print("\(Date())didWriteValueFor hexDataStr === ", hexDataStr)
//            if hexDataStr.hasSuffix("0D0A") {
//                let ms_model = "MS_MODE16\r\n".data(using: .utf8)
//                peripheral.writeValue(ms_model!, for: characteristic, type: CBCharacteristicWriteType.withResponse)
//            }
            if data.count > 0 {
                for i in 0 ..< data.count {
                    print("BT didWriteValueFor i = \(i), value = \(characteristic.value![i])")
                }
            }
        }
    }

    //显示属性权限
    func propertiesString(properties:CBCharacteristicProperties) -> String {
        var propertiesReturn:String = ""
        if (properties.rawValue & CBCharacteristicProperties.broadcast.rawValue) != 0 {
            propertiesReturn += "broadcast|"
        }
        if (properties.rawValue & CBCharacteristicProperties.read.rawValue) != 0 {
            propertiesReturn += "read|"
        }
        if (properties.rawValue & CBCharacteristicProperties.writeWithoutResponse.rawValue) != 0 {
            propertiesReturn += "writeWithoutResponse|"
        }
        if (properties.rawValue & CBCharacteristicProperties.write.rawValue) != 0 {
            propertiesReturn += "write|"
        }
        if (properties.rawValue & CBCharacteristicProperties.notify.rawValue) != 0 {
            propertiesReturn += "notify|"
        }
        if (properties.rawValue & CBCharacteristicProperties.indicate.rawValue) != 0 {
            propertiesReturn += "indicate|"
        }
        if (properties.rawValue & CBCharacteristicProperties.authenticatedSignedWrites.rawValue) != 0 {
            propertiesReturn += "authenticatedSignedWrites|"
        }
        if (properties.rawValue & CBCharacteristicProperties.extendedProperties.rawValue) != 0 {
            propertiesReturn += "extendedProperties|"
        }
        if (properties.rawValue & CBCharacteristicProperties.notifyEncryptionRequired.rawValue) != 0 {
            propertiesReturn += "notifyEncryptionRequired|"
        }
        if (properties.rawValue & CBCharacteristicProperties.indicateEncryptionRequired.rawValue) != 0 {
            propertiesReturn += "indicateEncryptionRequired|"
        }
        return propertiesReturn
    }
}


//MARK: - MAMapViewDelegate 地图代理
extension ViewController:MAMapViewDelegate{
    func mapView(_ mapView: MAMapView!, rendererFor overlay: MAOverlay!) -> MAOverlayRenderer! {
        if overlay.isKind(of: MAPolygon.self) {
            let renderer:MAPolygonRenderer = MAPolygonRenderer(overlay: overlay)
            renderer.lineWidth = 2.0
            //笔触颜色
            renderer.strokeColor = .clear
            return renderer
        }
        if overlay.isKind(of: MAPolyline.self) {
            let lineRender = MAPolylineRenderer(overlay: overlay)
            lineRender?.lineWidth = 2
            lineRender?.strokeColor = .blue
            lineRender?.lineJoin = .round
            lineRender?.lineCap = .round
            return lineRender
        }
//        if (overlay.isKind(of: MAMultiPolyline.self))
//        {
//            let renderer = MAMultiColoredPolylineRenderer.init(multiPolyline: overlay as? MAMultiPolyline)
//            renderer?.lineWidth = 8.0
//            renderer?.strokeColor = .red
//            renderer?.isGradient = true
//
//            return renderer;
//        }
        return nil
    }

    

    func mapView(_ mapView: MAMapView!, didUpdate userLocation: MAUserLocation!, updatingLocation: Bool) {
        guard updatingLocation else {
            return
        }
//        let longitude = userLocation.location.coordinate.longitude
//        let latitude = userLocation.location.coordinate.latitude
//        print("用户当前定位 经度 ==== \(longitude) 纬度 === \(latitude)")
//        let locationCoord:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
//        self.tempLocaList.append(locationCoord)
//        mapView.remove(self.polygonLine)
//        self.polygonLine = MAPolyline(coordinates: &tempLocaList, count: UInt(tempLocaList.count))
//        self.mapView.add(self.polygonLine)

//        let lat = changeToDu(dms: "30°47′58.9326171875052″")
//        let lon = changeToDu(dms: "103°56′56.249023437492″")
//        print("用户当前 经度 ==== \(lon) 纬度 === \(lat)")

    }

    func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! {

        if annotation.isKind(of: MAPointAnnotation.self) {
            let pointReuseIndetifier = "pointReuseIndetifier"
            var annotationView: MAPinAnnotationView? = mapView.dequeueReusableAnnotationView(withIdentifier: pointReuseIndetifier) as! MAPinAnnotationView?

            if annotationView == nil {
                annotationView = MAPinAnnotationView(annotation: annotation, reuseIdentifier: pointReuseIndetifier)
            }
            annotationView!.canShowCallout = true
            annotationView!.animatesDrop = true
            annotationView!.isDraggable = true
            annotationView!.rightCalloutAccessoryView = UIButton(type: UIButton.ButtonType.detailDisclosure)
            annotationView!.setSelected(true, animated: true)
//            let idx = annotations.index(of: annotation as! MAPointAnnotation)
//            annotationView!.pinColor = MAPinAnnotationColor(rawValue: idx!%3)!
            annotationView?.pinColor = .red
            return annotationView!
        }

        return nil
    }
}

//MARK: - AMapLocationManagerDelegate 定位代理
extension ViewController:AMapLocationManagerDelegate {
    func amapLocationManager(_ manager: AMapLocationManager!, didUpdate location: CLLocation!, reGeocode: AMapLocationReGeocode!) {
        let longitude = location.coordinate.longitude
        let latitude = location.coordinate.latitude
        print("当前定位 经度 ==== \(longitude) 纬度 === \(latitude)")
        let locationCoord:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
        self.tempLocaList.append(locationCoord)
        mapView.remove(self.polygonLine)
        self.polygonLine = MAPolyline(coordinates: &tempLocaList, count: UInt(tempLocaList.count))
        self.mapView.add(self.polygonLine)
    }
}




